package wiki.zimo.servlet.backstage;

import wiki.zimo.constant.Constant;
import wiki.zimo.dao.OrderDao;
import wiki.zimo.dao.OrderItemDao;
import wiki.zimo.dao.ProductDao;
import wiki.zimo.dao.UserDao;
import wiki.zimo.domain.Order;
import wiki.zimo.domain.Orderitem;
import wiki.zimo.domain.Product;
import wiki.zimo.domain.User;
import wiki.zimo.servlet.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @version v1.0
 * @auther: 子墨
 * @datetime: 2018/11/11 19:48
 * @description: 处理后台订单管理的servlet
 */
@WebServlet(value = "/orderManage")
public class OrderManageServlet extends BaseServlet {

    OrderDao orderDao = new OrderDao();
    OrderItemDao orderItemDao = new OrderItemDao();
    UserDao userDao = new UserDao();
    ProductDao productDao = new ProductDao();

    /**
     * @auther: 子墨
     * @date: 2018/11/11 19:52
     * @describe: 订单列表页
     * @param: [request, response]
     * @return: java.lang.String
     * @version v1.0
     */
    public String orderListPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Order> orders = orderDao.findAll();
        for (Order o : orders) {
            List<Orderitem> items = orderItemDao.findOrderitemsByOid(o.getOid());
            for (Orderitem item : items) {
                Product product = productDao.findOneById(item.getPid());
                item.setProduct(product);
            }
            o.setOrderItems(items);
            User user = userDao.findOneById(o.getUid());
            o.setUser(user);
        }
        System.out.println(orders);
        request.setAttribute(Constant.ORDERS, orders);
        return Constant.URL_BACKSTAGE_ORDER_LIST;
    }

    /**
     * @auther: 子墨
     * @date: 2018/11/11 20:45
     * @describe: 订单发货接口
     * @param: [request, response]
     * @return: java.lang.String
     * @version v1.0
     */
    public String deliveryProduct(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String oid = request.getParameter("oid");
        Order order = orderDao.findOneById(oid);
        if (order != null && order.getState() == Constant.ORDER_PAY_YET) {
            order.setState(Constant.ORDER_DELIVERY);
            orderDao.update(order);
            request.setAttribute(Constant.MSG, "发货成功");
            return orderListPage(request, response);
        }
        request.setAttribute(Constant.MSG, "不允许发货此类订单");
        return orderListPage(request, response);
    }
}
